<template>
  <div>
    <div class="app-container">
      <div class="page_header">{{typeId?'编辑':'添加'}}产品分类</div>
      <el-col :span="12">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入单行文本分类名称" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="formData.sort" placeholder="越大越靠前" :max="50" :step="1"></el-input-number>
          </el-form-item>

          <el-form-item label="上传图片" required>
            <el-upload
              ref="url"
              :file-list="urlfileList"
              :headers="urlHeaders"
              :action="urlAction"
              :on-remove="handleRemove"
              :limit="1"
              :before-upload="urlBeforeUpload"
              :on-success="handleFileSuccess"
              list-type="picture"
              accept="image/*"
            >
              <el-button :disabled="disabled" size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的 jpg,png 文件</div>
            </el-upload>
          </el-form-item>

          <el-form-item size="large">
            <el-button type="primary" :disabled="pending" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
  </div>
</template>

<script>
import { getProtypeDetail, addProtype, updateProtype } from '@/api/product/protype'
import { uploadUrl } from '@/settings.js'
import { getToken } from '@/utils/auth'
export default {
  name: 'Protypeedit',
  components: {},
  data() {
    return {
      formData: {
        name: undefined,
        sort: 1,
        url: null
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入单行文本分类名称',
            trigger: 'blur'
          }
        ],
        sort: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ]
      },

      urlAction: uploadUrl,
      urlHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      urlfileList: [],
      //
      pending: false,
      disabled:false
    }
  },
  computed: {
    typeId() {
      return this.$route.query.id
    }
  },
  async mounted() {
    if (this.typeId) {
      try {
        this.disabled=true;
        const res = await getProtypeDetail(this.typeId)
        this.formData.name = res.data.name
        this.formData.sort = res.data.sort
        this.urlfileList = res.data.urlJson.map((per) => {
          return {
            name: per.name,
            url: per.url,
            response: {
              data: per
            }
          }
        })
      } catch (error) {
        console.log(error)
      }
    } else {
      this.resetForm()
    }
  },
  // 编辑类不缓存
  // async activated() {
  // },
  methods: {
    submitForm() {
      this.$refs['elForm'].validate(async (valid) => {
        if (!valid) return

        if (this.$refs.url.uploadFiles.length === 0) {
          this.$message.error('请上传图片')
          return
        }

        this.formData.url = this.$refs['url'].uploadFiles.map((per) => per.response.data)

        this.pending = true
        try {
          const fetchFn = this.typeId ? updateProtype : addProtype
          const res = await fetchFn({
            ...this.formData,
            id: this.typeId ? this.typeId : undefined
          })
          if (res.code === 200) {
            this.msgSuccess(res.msg)
            this.$closeNowTagsView()
          }
        } catch (error) {
          console.log(error)
        }
        this.pending = false
      })
    },
    handleRemove(file, fileList) {
      this.disabled=false;
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$refs['url'].clearFiles()
    },
    urlBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('image/*').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件')
      }
      return isRightSize && isAccept
    },
    handleFileSuccess(response, file, fileList) {
      console.log(fileList)
      if (response.code !== 200) {
        const index = fileList.findIndex((per) => per.uid === file.uid)
        fileList.splice(index, 1)
        this.$message({ message: response.msg, type: 'error' })
      }
    }
  }
}
</script>

<style lang='scss'>
</style>
